package kz.pro.server.services;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import kz.pro.server.dao.UserDAOImpl;
import kz.pro.shared.entity.UserEntity;
import kz.pro.shared.services.UserService;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;


@Service("userService")
public class UserServicesImpl implements UserService{
	
	ApplicationContext appletContext = new ClassPathXmlApplicationContext("/xml/bean.xml");
	UserDAOImpl userDAO = (UserDAOImpl)appletContext.getBean("userDAO");
	
	@PostConstruct
	public void init() throws Exception{
		
	}
	
	
	@PreDestroy
	public void destroy(){
		
	}


	@Override
	public UserEntity findUser(BigDecimal userId) {
		
		return userDAO.getUserById(userId);
	}


	@Override
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
	public void saveUser(String name, String surname, String phoneNumber,
			String phoneType) throws Exception {
		UserEntity user = new UserEntity();
		user.setName(name);
		user.setSurname(surname);
		user.setPhoneNumber(phoneNumber);
		user.setPhoneType(phoneType);
	
		userDAO.save(user);
		
	}


	@Override
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)

	public void updateUser(BigDecimal userId, String name, String surname,
			String phoneNumber, String phoneType) throws Exception {
		
		UserEntity user = userDAO.getUserById(userId);
		
		if(user!=null){
			user.setName(name);
			user.setSurname(surname);
			user.setPhoneNumber(phoneNumber);
			user.setPhoneType(phoneType);
			userDAO.update(user);
		}
		
	}


	@Override
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
	public void deleteUser(UserEntity user) throws Exception {
		
		
		if(user!=null){
			userDAO.remove(user);
		}
		
	}


	@Override
	public List<UserEntity> userList() {
	
		List<UserEntity> userList = userDAO.listUsers();
		return userList;
	}


	@Override
	public void hello() {
		
		userDAO.hello();
		
	}
 }
